/*
Usage:
var stack = require('stack')();
try
{
    // num, str -- variables existed
    // initial, terminate -- functions existed
    eval(s.push('num;str;initial()', '100;\'asdf\';terminate()'));
}
finally
{
    eval(s.pop());
}
*/
var stack = function(){
  return {
      push : function(staVars,newVals){
          this.setNewsCmds = '';
          this.backOldCmds = '';
          if (staVars.constructor !== String || newVals.constructor !== String)
              throw new Error('params invalid');
          var staArray = staVars.split(';');
          var newArray = newVals.split(';');
          if (staArray.length != newArray.length)
              throw new Error('item\'s number not equals');
          var functionRegex = /\(.*\)\s*;?\s*$/;
          for (let idx = 0; idx < staVars.length; idx++){
              if (functionRegex.test(staVars[idx])){
                  this.setNewsCmds += staVars[idx] + ';';
                  this.backOldCmds += newVals[idx] + ';';
              }else{
                  this.setNewsCmds += 'var STACKTMPVAR' + idx + '=' + staVars[idx] + ';';
                  this.setNewsCmds += staVars[idx] + '=' + newVals[idx] + ';';
                  this.backOldCmds += staVars[idx] + '=' + 'STACKTMPVAR' + idx + ';';
              }
          }
          return this.setNewsCmds;
      },
      pop : function(){
          return this.backOldCmds;
      }
  };
};
module.exports = stack;